package com.taoge.webrtc.netty;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

/**
 * NettyServerBootstrap Netty服务器配置
 */

@Component
@RequiredArgsConstructor
@Slf4j
public class NettyServerBootstrap implements ApplicationRunner {

    @Value("${netty.ip}")
    private String ip;

    @Value("${netty.port}")
    private int port;

    @Value("${netty.path}")
    private String path;

    private final NettyChannelInitializer nettyChannelInitializer;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            ServerBootstrap sb = new ServerBootstrap();
            sb.option(ChannelOption.SO_BACKLOG, 128);
            sb.group(group, bossGroup) // 绑定线程池
                    .channel(NioServerSocketChannel.class) // 指定使用的channel
                    .localAddress(port)// 绑定监听端口
                    //部署需要改成官网ip，否则只能本地连接
//                    .localAddress(ip, port)// 绑定ip和端口
                    .childHandler(nettyChannelInitializer);
            ChannelFuture cf = sb.bind().sync(); // 服务器异步创建绑定
            log.info("NettyServer启动成功，连接地址：ws://{}:{}{}", ip, port, path);
            cf.channel().closeFuture().sync(); // 关闭服务器通道 ~~~~~会阻塞主进程，一般用于单元测试
        } catch (InterruptedException e) {
            log.error("NettyServer启动异常：{}", e.getMessage());
        } finally {
            bossGroup.shutdownGracefully().syncUninterruptibly();
            group.shutdownGracefully().syncUninterruptibly();
        }
    }

}
